import { EventNames, emitter } from "@renderer/services/event-service";
import logger from "@shared/logger/renderer-logger";
import type { Message } from "@shared/triplit/types";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { usePrivacyMode } from "./use-privacy-mode";
import { useToolBar } from "./use-tool-bar";

const { threadService, messageService } = window.service;

export function useMessageActions() {
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const { t } = useTranslation("translation", { keyPrefix: "message" });
  const { selectedModelId } = useToolBar();
  const { privacyState } = usePrivacyMode();

  const handleRefreshMessage = async (
    messageId: string,
    onRefresh: (messageId: string) => Promise<void>,
  ) => {
    await onRefresh(messageId);
  };

  const handleEditAssistantMessage = () => {
    setIsEditDialogOpen(true);
  };

  const handleEditUserMessage = (message: Message) => {
    emitter.emit(EventNames.MESSAGE_EDIT, message);
  };

  const handleCreateNewBranch = async (
    message: Message,
    providerId: string,
    triggerBy?: "first-send-message" | "without-send-message",
    isNewTab?: boolean,
  ): Promise<{ threadId: string } | null> => {
    try {
      const result = await threadService.createNewBranch(
        message,
        t("context-menu.new-thread-title"),
        selectedModelId,
        providerId,
        privacyState?.isPrivate || false,
        triggerBy,
        isNewTab,
      );

      if (!result) {
        return null;
      }

      // await setActiveTabId(result.tabId);
      return result;
    } catch (error) {
      logger.error("Error creating new branch:", { error });
      toast.error(t("context-menu.create-new-branch-error"));
      return null;
    }
  };

  const handleDeleteMessage = async (messageId: string, threadId: string) => {
    try {
      await messageService.deleteMessage(messageId, threadId);
      toast.success(t("delete-success"));
    } catch (error) {
      logger.error("Error deleting message:", { error });
      toast.error(t("delete-error"));
    }
  };

  return {
    isEditDialogOpen,
    setIsEditDialogOpen,
    handleRefreshMessage,
    handleEditAssistantMessage,
    handleEditUserMessage,
    handleCreateNewBranch,
    handleDeleteMessage,
  };
}
